<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />

    <!-- 表格：展示excel的内容 -->
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployees } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header

      // 1. 根据后端需要格式转化
      const transExcel = this.transExcel(results, header)
      // console.log(transExcel)
      // 2. 发送请求
      await importEmployees(transExcel)
      // 3. 成功跳转路由
      this.$message.success('导入成功')
      // 4. 跳转路由
      this.$router.push('/employees')
    },

    transExcel(results, header) {
      console.log('格式化excel之后的内容是', results, header)
      // 根据后端需要格式转化
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      const znKeys = Object.keys(results[0])
      // 拿到Excel文件里面的属性名
      // console.log(znKeys)
      return results.map((item) => {
        // 创建一个新对象 返回的值是一个英文 value是item的值
        const obj = {}
        // console.log(item)
        znKeys.forEach((znkey) => {
          // 拿到中文转化后的值 进行赋值
          const enKeys = mapInfo[znkey]
          if (enKeys === 'timeOfEntry' || enKeys === 'correctionTime') {
            obj[enKeys] = new Date(formatExcelDate(item[znkey]))
          } else {
            // 在进行赋值
            // console.log(obj[enKeys])
            // console.log(enKeys)
            // console.log(item[znkey])
            obj[enKeys] = item[znkey]
            // console.log(obj)
          }
        })
        return obj
      })
    }
  }
}
</script>
